package com.jch.sc.server;

import com.jch.sc.codec.ObjDecoder;
import com.jch.sc.codec.ObjEncoder;
import com.jch.sc.msg.Request;
import com.jch.sc.msg.Response;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class ServerSocket implements Runnable {

    @Override
    public void run() {
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();

        ServerBootstrap b = new ServerBootstrap()
                .group(worker, worker)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,128)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(
                                new ObjDecoder(Request.class), // 解码转为Request | 接收客户端的请求 | 客户端解码转为Response
                                new ObjEncoder(Response.class),// 编码转换Response | 发送响应信息 | 客户端编码转换Request
                                new ServerHandler() // 业务处理器
                        );
                    }
                });
        try {
            ChannelFuture channelFuture = b.bind(1129).sync();
            System.out.println("netty server socket start.");
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }
}
